<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <device-channel-selector
        v-model="deviceChannelSelection"
        @change="handleDeviceChannelChange"
        device-label="设备"
        channel-label="通道"
        class="device-channel-selector-inline"
      />
      <el-form-item label="位置编码" prop="lcCode">
        <el-input
          v-model="queryParams.lcCode"
          placeholder="请输入位置编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼栋" prop="buildingName">
        <el-input
          v-model="queryParams.buildingName"
          placeholder="请输入楼栋"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单元" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入单元"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电梯" prop="elevatorName">
        <el-input
          v-model="queryParams.elevatorName"
          placeholder="请输入电梯"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in statusOptions"-->
<!--            :key="dict.dictValue"-->
<!--            :label="dict.dictLabel"-->
<!--            :value="dict.dictValue"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="告警时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 340px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:bevent:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="buildingEventList"
      row-key="locationId"
      :default-expand-all="false"
      :tree-props="{children: 'eventDetails', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="位置编码" align="center" prop="lcCode" width="200" />
      <el-table-column label="位置名称" align="center" prop="lcName" width="280" />
      <el-table-column label="设备号" align="center" prop="deviceNo" width="80" />
      <el-table-column label="通道" align="center" prop="chanel" width="80"/>
      <el-table-column label="起止米标" align="center" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.markerStart}}-{{scope.row.markerEnd}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最高温度" align="center" prop="maxTemperature" width="100" />
      <el-table-column label="最低温度" align="center" prop="minTemperature" width="100" />
      <el-table-column label="事件数量" align="center" prop="eventCount" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.eventCount > 0 ? 'danger' : 'info'"
                  @click="handleViewDetails(scope.row)"  style="cursor: pointer;">
            {{ scope.row.eventCount }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最新时间" align="center" prop="latestTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.latestTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="楼栋" align="center" prop="buildingName" width="120" />-->
<!--      <el-table-column label="单元" align="center" prop="unitName" width="120" />-->
<!--      <el-table-column label="电梯" align="center" prop="elevatorName" width="120" />-->
<!--      <el-table-column label="楼层" align="center" prop="floorName" width="120" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetails(scope.row)"
            v-hasPermi="['project:bevent:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleRefreshDetails(scope.row)"
            v-hasPermi="['project:bevent:query']"
          >刷新</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 事件详情对话框 -->
    <el-dialog :title="eventDetailTitle" :visible.sync="eventDetailOpen" width="1200px" append-to-body>
      <!-- 添加电梯楼层信息展示 -->
      <el-descriptions :column="4" border size="medium" style="margin-bottom: 20px;">
        <el-descriptions-item label="设备-通道">{{ currentLocationInfo.deviceNo || '-' }}-{{ currentLocationInfo.chanel || '-' }}</el-descriptions-item>
        <el-descriptions-item label="最高温度">
          <span :style="{ color: currentLocationInfo.maxTemperature > 60 ? '#F56C6C' : '#67C23A' }">
            {{ currentLocationInfo.maxTemperature || '-' }}°C
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="最低温度">
          <span :style="{ color: currentLocationInfo.minTemperature < 0 ? '#409EFF' : '#67C23A' }">
            {{ currentLocationInfo.minTemperature || '-' }}°C
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="起止米标">
          {{ currentLocationInfo.markerStart || 0 }} - {{ currentLocationInfo.markerEnd || 0 }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 批量操作工具栏 -->
      <el-row :gutter="10" class="mb8" style="margin-bottom: 15px;">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleBatchHandle"
            v-hasPermi="['project:bevent:edit']"
          >批量处理</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-circle-close"
            size="mini"
            @click="cancelSelection"
          >取消选择</el-button>
        </el-col>
        <div style="float: right;">
          <span style="margin-right: 10px; color: #606266;">已选择 {{ selectedRows.length }} 项</span>
        </div>
      </el-row>

      <el-table
        ref="eventDetailTable"
        :data="eventDetailList"
        v-loading="detailLoading"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="事件编号" align="center" prop="eventNo" width="180" />
        <el-table-column label="报警米标" align="center" prop="meterMark" width="80" />
        <el-table-column label="最高温度" align="center" prop="maxTemperature" width="80" />
        <el-table-column label="最低温度" align="center" prop="minTemperature" width="80" />
        <el-table-column label="平均温度" align="center" prop="avgTemperature" width="80" />
        <el-table-column prop="eventStatus" label="事件状态" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.alarm_state" :value="scope.row.eventStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="告警开始时间" align="center" prop="alarmStartTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.alarmStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="告警关闭时间" align="center" prop="alarmCloseTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.alarmCloseTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleSingleHandle(scope.row)"
              v-hasPermi="['project:bevent:edit']"
            >处理</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="eventDetailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 处理对话框 -->
    <el-dialog :title="handleTitle" :visible.sync="handleOpen" width="500px" append-to-body>
      <el-form ref="handleForm" :model="handleForm" :rules="handleRules" label-width="80px">
        <el-form-item label="处理意见" prop="handledResult">
          <el-input
            v-model="handleForm.handledResult"
            type="textarea"
            placeholder="请输入处理意见"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHandleForm">确 定</el-button>
        <el-button @click="cancelHandle">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBuildingEvent, getEventDetails  } from "@/api/project/bevent"
import { handleEvent, handleEventBatch  } from "@/api/project/event"
import DeviceChannelSelector from '@/components/DeviceChannelSelector';

export default {
  name: "Bevent",
  components: {
    DeviceChannelSelector
  },
  dicts: ['alarm_type', 'alarm_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      detailLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 楼栋告警表格数据
      buildingEventList: [],
      // 事件详情数据
      eventDetailList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      eventHandleOpen: false,
      eventDetailOpen: false,
      handleOpen: false,
      // 通道字典
      chanelOptions: [],
      // 状态字典
      statusOptions: [],
      // 报警类型字典
      alarmTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceNo: null,
        chanel: null,
        lcCode: null,
        buildingName: null,
        unitName: null,
        elevatorName: null,
        status: null,
      },
      // 设备通道选择
      deviceChannelSelection: {
        deviceNo: '',
        channelNo: ''
      },
      // 事件处理表单
      eventHandleForm: {
        eventId: null,
        handledResult: null,
        handledBy: null
      },
      // 事件处理表单校验
      eventHandleRules: {
        handledResult: [
          { required: true, message: "处理结果不能为空", trigger: "blur" }
        ],
        handledBy: [
          { required: true, message: "处理人不能为空", trigger: "blur" }
        ]
      },
      eventHandleTitle: "",
      eventDetailTitle: "",
      handleTitle: "",
      // 当前选中位置信息
      currentLocationInfo: {
        deviceNo:'',
        chanel: null,
        buildingName: '',
        unitName: '',
        elevatorName: '',
        floorName: '',
        maxTemperature: null,
        minTemperature: null,
        markerStart: null,
        markerEnd: null
      },
      // 选中的行数据
      selectedRows: [],
      // 当前处理的事件ID
      currentHandleIds: [],
      // 处理表单
      handleForm: {
        handledResult: ""
      },
      // 处理表单校验
      handleRules: {
        handledResult: [
          { required: true, message: "处理意见不能为空", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    // 是否禁用批量操作按钮
    multiple() {
      return this.selectedRows.length === 0;
    }
  },
  created() {
    this.getList()
    this.getDicts("alarm_state").then(response => {
      console.log('报警状态字典:', response.data)
      this.statusOptions = response.data
    })
    this.getDicts("alarm_type").then(response => {
      console.log('报警类型字典:', response.data)
      this.alarmTypeOptions = response.data
    })
  },
  methods: {
    // 处理设备通道变更
    handleDeviceChannelChange(selection) {
      console.log('收到设备通道变更:', selection);
      this.queryParams.deviceNo = selection.deviceNo;
      this.queryParams.chanel = selection.channelNo;
    },
    /** 查询楼栋告警列表 */
    getList() {
      this.loading = true
      this.queryParams.deviceNo = this.deviceChannelSelection.deviceNo;
      this.queryParams.chanel = this.deviceChannelSelection.channelNo;
      console.log('查询参数:', this.queryParams)
      const queryData = {
        ...this.queryParams,
        params: {
          ...this.queryParams.params
        }
      }

      // 设置时间范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        queryData.params.beginTime = this.dateRange[0]
        queryData.params.endTime = this.dateRange[1]
      }

      listBuildingEvent(queryData).then(response => {
        this.buildingEventList = response.rows.map(item => {
          return {
            ...item,
            hasChildren: item.eventCount > 0
          }
        })
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 查看楼层详情 */
    handleViewDetails(row) {
      this.eventDetailTitle = "楼层告警详情 - " + row.lcName

      // 设置当前选中位置的信息
      this.currentLocationInfo = {
        locationId: row.locationId,
        buildingName: row.buildingName,
        unitName: row.unitName,
        elevatorName: row.elevatorName,
        floorName: row.floorName,
        maxTemperature: row.maxTemperature,
        minTemperature: row.minTemperature,
        markerStart: row.markerStart,
        markerEnd: row.markerEnd,
        deviceNo: row.deviceNo,
        chanel: row.chanel
      }

      // 清空选择
      this.selectedRows = []

      getEventDetails({
        locationId: row.locationId,
        deviceNo: row.deviceNo,
        chanel: row.chanel,
        beginTime: this.dateRange && this.dateRange[0],
        endTime: this.dateRange && this.dateRange[1],
        eventStatus: row.status
      }).then(response => {
        this.eventDetailList = response.data
        this.eventDetailOpen = true
        this.detailLoading = false
      })
    },
    /** 刷新楼层详情 */
    handleRefreshDetails(row) {
      this.detailLoading = true
      const index = this.buildingEventList.findIndex(item => item.locationId === row.locationId)
      if (index !== -1) {
        getEventDetails({
          locationId: row.locationId,
          deviceNo: row.deviceNo,
          chanel: row.chanel,
          beginTime: this.dateRange && this.dateRange[0],
          endTime: this.dateRange && this.dateRange[1],
          eventStatus: row.status
        }).then(response => {
          this.buildingEventList[index].eventDetails = response.data
          this.$modal.msgSuccess("刷新成功")
          this.detailLoading = false
        })
      }
    },
    /** 表格选择项改变 */
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    /** 取消选择 */
    cancelSelection() {
      this.$refs.eventDetailTable.clearSelection();
      this.selectedRows = [];
    },
    /** 单个处理按钮操作 */
    handleSingleHandle(row) {
      this.currentHandleIds = [row.id];
      this.handleTitle = "处理事件 - " + row.eventNo;
      this.handleForm.handledResult = "";
      this.handleOpen = true;
    },
    /** 批量处理按钮操作 */
    handleBatchHandle() {
      if (this.selectedRows.length === 0) {
        this.$modal.msgError("请先选择要处理的事件");
        return;
      }
      const eventNos = this.selectedRows.map(item => item.eventNo).join(', ');
      this.currentHandleIds = this.selectedRows.map(item => item.id);
      this.handleTitle = "批量处理事件 - 共" + this.selectedRows.length + "项";
      this.handleForm.handledResult = "";
      this.handleOpen = true;
    },
    /** 提交处理表单 */
    submitHandleForm() {
      this.$refs["handleForm"].validate(valid => {
        if (valid) {
          const handledBy = this.$store.state.user.name;

          // 创建请求数据对象
          const requestData = {
            handledResult: this.handleForm.handledResult,
            handledBy: handledBy
          };

          if (this.currentHandleIds.length === 1) {
            // 单个处理
            requestData.eventId = this.currentHandleIds[0];
            this.handleSingleEvent(requestData);
          } else {
            // 批量处理
            requestData.eventIds = this.currentHandleIds;
            this.handleBatchEvent(requestData);
          }
        }
      })
    },

    /** 处理单个事件 */
    handleSingleEvent(data) {
      handleEvent(data).then(response => {
        this.$modal.msgSuccess("处理成功");
        this.handleOpen = false;
        this.resetHandleForm();
        // 刷新事件详情列表
        this.handleRefreshEventDetails();
        this.getList();
      }).catch(error => {
        console.error('处理事件失败:', error);
        this.$modal.msgError("处理失败");
      });
    },

    /** 批量处理事件 */
    handleBatchEvent(data) {
      // 将eventIds中的数字转换为Long类型（字符串形式）
      const requestData = {
        eventIds: data.eventIds.map(id => id.toString()), // 转换为字符串
        handledResult: data.handledResult,
        handledBy: data.handledBy
      };

      handleEventBatch(requestData).then(response => {
        this.$modal.msgSuccess(response.msg || `成功处理 ${data.eventIds.length} 个事件`);
        this.handleOpen = false;
        this.resetHandleForm();
        // 刷新事件详情列表
        this.handleRefreshEventDetails();
        this.getList();
      }).catch(error => {
        console.error('批量处理事件失败:', error);
        this.$modal.msgError("批量处理失败");
      });
    },

    /** 刷新事件详情列表 */
    handleRefreshEventDetails() {
      if (this.eventDetailOpen && this.currentLocationInfo.deviceNo) {
        this.detailLoading = true;
        getEventDetails({
          locationId: this.currentLocationInfo.locationId,
          deviceNo: this.currentLocationInfo.deviceNo,
          chanel: this.currentLocationInfo.chanel,
          beginTime: this.dateRange && this.dateRange[0],
          endTime: this.dateRange && this.dateRange[1],
          eventStatus: this.currentLocationInfo.status
        }).then(response => {
          this.eventDetailList = response.data;
          this.detailLoading = false;
        });
      }
    },

    /** 重置处理表单 */
    resetHandleForm() {
      this.handleForm = {
        handledResult: ""
      };
      this.currentHandleIds = [];
    },
    /** 取消处理 */
    cancelHandle() {
      this.handleOpen = false
      this.resetForm("handleForm")
      this.currentHandleIds = []
    },
    /** 查看单个事件 */
    handleViewEvent(row) {
      this.eventDetailTitle = "事件详情 - " + row.eventNo
      this.eventDetailList = [row]
      this.eventDetailOpen = true
    },
    /** 处理事件 */
    handleHandleEvent(row) {
      this.eventHandleTitle = "处理事件 - " + row.eventNo
      this.eventHandleForm.eventId = row.id
      this.eventHandleForm.handledResult = null
      this.eventHandleForm.handledBy = this.$store.state.user.name
      this.eventHandleOpen = true
    },
    /** 提交事件处理 */
    submitEventHandle() {
      this.$refs["eventHandleForm"].validate(valid => {
        if (valid) {
          handleEvent(this.eventHandleForm).then(response => {
            this.$modal.msgSuccess("处理成功")
            this.eventHandleOpen = false
            this.getList()
          })
        }
      })
    },
    /** 取消事件处理 */
    cancelEventHandle() {
      this.eventHandleOpen = false
      this.resetForm("eventHandleForm")
    },

    /** 导出按钮操作 */
    handleExport() {
      // 同步设备通道选择到查询参数
      this.queryParams.deviceNo = this.deviceChannelSelection.deviceNo;
      this.queryParams.chanel = this.deviceChannelSelection.channelNo;

      this.download('project/bevent/export', {
        ...this.queryParams
      }, `buildingEvent_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}
.el-table .success-row {
  background: #f0f9eb;
}
</style>
